﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AMS.DataAccess.Sys.Interfaces;
using AMS.DataAccess.Sys.BO;

public partial class Security_AllRoles : BaseWorkPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //CheckPageAccess("view_role_channel");
        if (!IsPostBack)
        {
            //btnAddRole.Visible = CheckAccess("edit_function");
            //btnSave.Visible = CheckAccess("change_role_function");
            //lkAddUser.Visible = CheckAccess("add_user");
            //lkDeleteUser.Visible = CheckAccess("delete_user");
            DoDataBind();
        }
    }

    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        DoDataBind();
    }

    #region Properties
    IRoleManager _roleMgr;
    IModuleManager _moduleMgr;
    IRoleManager RoleMgr
    {
        get
        {
            if (_roleMgr == null)
            {
                _roleMgr = ManagerFactory.CreateRoleManager();
            }

            return _roleMgr;
        }
    }

    IModuleManager ModuleMgr
    {
        get 
        {
            if (_moduleMgr == null)
            {
                _moduleMgr = ManagerFactory.CreateModuleManager();
            }

            return _moduleMgr;
        }
    }
    #endregion

    #region DataBind
    void DoDataBind()
    {
        BindRoles();
        BindSystems();
        if (drpSystems.Items.Count > 0)
        {
            int systemId = int.Parse(drpSystems.SelectedValue);
            BuildModuleTree(systemId);
        }
        else
        {
            tvModules.Nodes.Clear();
        }

        chklistFunctions.Items.Clear();
    }

    protected string FormatDateTime(object value, bool showTime)
    {
        return Utils.FormateDateTime(value, showTime);
    }

    void BindRoles()
    {
        List<RoleInfo> roles = RoleMgr.GetAllRoles(CallContext);
        lstRole.DataSource = roles;
        lstRole.DataTextField = "RoleName";
        lstRole.DataValueField = "AID";
        lstRole.DataBind();
    }

    void BindSystems()
    {
        List<ModuleInfo> modules = ModuleMgr.GetSystems(CallContext);
        drpSystems.DataSource = modules;
        drpSystems.DataTextField = "ModuleName";
        drpSystems.DataValueField = "AID";
        drpSystems.DataBind();
    }

    void BuildModuleTree(int moduleId)
    {
        ModuleInfo module = ModuleMgr.GetModule(CallContext, moduleId, true);
        tvModules.Nodes.Clear();
        TreeNode topNode = new TreeNode(module.ModuleName);
        topNode.Value = module.AID.ToString();
        topNode.SelectAction = TreeNodeSelectAction.Select;
        //topNode.NavigateUrl = "javascript:void(0);";
        tvModules.Nodes.Add(topNode);
        if (module.Modules != null && module.Modules.Count > 0)
        {
            AddSubNodes(topNode, module);
        }
    }

    void AddSubNodes(TreeNode node, ModuleInfo currentModule)
    {
        foreach (ModuleInfo subModule in currentModule.Modules)
        {
            TreeNode subNode = new TreeNode(subModule.ModuleName);
            subNode.Value = subModule.AID.ToString();
            subNode.SelectAction = TreeNodeSelectAction.Select;
            //subNode.NavigateUrl = "javascript:void(0);";
            node.ChildNodes.Add(subNode);
            if (subModule.Modules != null && subModule.Modules.Count > 0)
            {
                AddSubNodes(subNode, subModule);
            }
        }
    }

    void BindRoleUsers(int roleId)
    {
        IUserManager userMgr = ManagerFactory.CreateUserManager();
        List<UserInfo> users = userMgr.GetUsersByRole(CallContext, roleId);
        gv.DataSource = users;
        gv.DataKeyNames = new string[] { "AID" };
        gv.DataBind();
        if (users == null || users.Count == 0)
        {
            lblUserMsg.Visible = true;
        }
        else
        {
            lblUserMsg.Visible = false;
        }
    }

    void BindRoleFunctions(int selecteRoleID)
    {
        if (chklistFunctions.Items.Count > 0)
        {
            if (tvModules.SelectedNode == null)
            {
                return;
            }

            int selectModuleID = int.Parse(tvModules.SelectedNode.Value);
            List<FunctionInfo> functions = RoleMgr.GetPrivilagesByModule(CallContext, selecteRoleID, selectModuleID);
            if (functions == null)
            {
                foreach (ListItem item in chklistFunctions.Items)
                {
                    item.Selected = false;
                }
            }
            else
            {
                List<int> ids = new List<int>();
                foreach (FunctionInfo fun in functions)
                {
                    ids.Add(fun.AID);
                }

                // Check the items
                foreach (ListItem item in chklistFunctions.Items)
                {
                    int value = int.Parse(item.Value);
                    if (ids.Contains(value))
                    {
                        item.Selected = true;
                    }
                    else
                    {
                        item.Selected = false;
                    }
                }
            }
        }
    }
    #endregion

    protected void tvModules_SelectedNodeChanged(object sender, EventArgs e)
    {
        int moduleId = int.Parse(tvModules.SelectedNode.Value);
        IFunctionManager funMgr = ManagerFactory.CreateFunctionManager();
        List<FunctionInfo> functions = funMgr.GetFunctions(CallContext, moduleId);
        chklistFunctions.DataSource = functions;
        chklistFunctions.DataTextField = "FunctionName";
        chklistFunctions.DataValueField = "AID";
        chklistFunctions.DataBind();

        lblNoFunctions.Visible = (functions.Count == 0) ;
        if (lstRole.SelectedIndex >= 0)
        {
            int roleId = int.Parse(lstRole.SelectedValue);
            BindRoleFunctions(roleId);
        }
    }

    protected void lstRole_SelectedIndexChanged(object sender, EventArgs e)
    {
        int selecteRoleID = int.Parse(lstRole.SelectedValue);
        BindRoleFunctions(selecteRoleID);
        BindRoleUsers(selecteRoleID);
    }

    protected void lkAddRoleSubmit_Click(object sender, EventArgs e)
    {
        string selected = lstRole.SelectedValue;
        BindRoles();

        if (!string.IsNullOrEmpty(selected))
        {
            ListItem item = lstRole.Items.FindByValue(selected);
            if (item != null)
            {
                item.Selected = true;
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (tvModules.SelectedNode == null)
        {
            return;
        }

        if (chklistFunctions.Items.Count == 0)
        {
            return;
        }

        int selectedModuleID = int.Parse(tvModules.SelectedNode.Value);
        int selectedRoleID = int.Parse(lstRole.SelectedValue);

        List<int> added = new List<int>();
        List<int> deleted = new List<int>();
        foreach (ListItem item in chklistFunctions.Items)
        {
            int selecteFunctionID = int.Parse(item.Value);
            if (item.Selected)
            {
                added.Add(selecteFunctionID);
            }
            else
            {
                deleted.Add(selecteFunctionID);
            }
        }

        RoleMgr.BatchUpdatePrivilage(CallContext, selectedRoleID, added, deleted);
        MsgInfo("更新成功");
    }
    protected void lkAfterAddUser_Click(object sender, EventArgs e)
    {
        if (lstRole.SelectedIndex < 0)
        {
            return;
        }

        int selectedRoleId = int.Parse(lstRole.SelectedValue);
        BindRoleUsers(selectedRoleId);
    }
    protected void lkDeleteUser_Click(object sender, EventArgs e)
    {
        if (lstRole.SelectedIndex < 0)
        {
            return;
        }

        int selectedRoleId = int.Parse(lstRole.SelectedValue);
        List<int> users = Utils.GetGridViewCheckItemIDs(gv);
        int count = RoleMgr.BatchDeleteRoleUsers(CallContext, selectedRoleId, users);
        BindRoleUsers(selectedRoleId);
        MsgInfo("成功: " +count.ToString());
    }
}
